import { ref } from 'vue';
import { Modal } from '@jecloud/ui';
import ListenerExpress from '@/components/form-field-config/components/expression-designer.vue';

/**
 *
 * @param {Object} options
 * @param {String} title 标题
 * @param {String} value  值
 * @param {Function} callback 回调函数
 *
 */

export function ListenerExpressModal(options) {
  const { title, callback, value, key, funcId } = options;
  const recordData = {
    title: title ? title : '表达式设计器',
    value: value || '',
    key,
    funcId,
  };
  const dataRef = ref(recordData);
  const ListenerExpressRef = ref();
  let modal = null; // 窗口对象

  // 确认操作
  const okButton = function () {
    const expressionTextareaValue = ListenerExpressRef.value.expressionTextareaValue;
    if (expressionTextareaValue && expressionTextareaValue != '') {
      callback?.({
        key,
        value: ListenerExpressRef.value.expressionTextareaValue,
      });
      modal.close();
    } else {
      Modal.alert('请生成表达式', 'error');
    }
  };

  // 初始选中值
  const onShow = function ({ $modal }) {
    modal = $modal;
  };

  const ListenerExpressSolt = () => {
    return (
      <ListenerExpress
        ref={ListenerExpressRef}
        recordData={dataRef.value}
        bodyBorder
        allowDeselect={false}
        onCellDblclick={okButton}
      />
    );
  };

  return Modal.window({
    title: dataRef.value.title,
    maximizable: false,
    width: '1000px',
    height: 'auto',
    bodyStyle: { padding: '0 20px' },
    headerStyle: { height: '60px' },
    onShow,
    okButton: {
      closable: false,
      handler: okButton,
    },
    cancelButton: true,
    slots: {
      default: ListenerExpressSolt,
    },
  });
}
